<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px" v-loading="dataForm.loading">
      <el-row>
        <el-col :span="24">
          <el-form-item label="展会名称" prop="tid">
            <el-select placeholder="请选择展会" v-model="dataForm.tid" clearable filterable :disabled="dataForm.id">
              <el-option v-for="option in templates" :key="option.id" :label="option.template" :value="option.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务名称" prop="tskName">
            <el-input v-model="dataForm.tskName" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!--任务负责人-->
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务负责人">
            <el-checkbox @change="handleCheckAllChange" v-model="allStufs">全选</el-checkbox>
          </el-form-item>
        </el-col>
        <el-form-item style="margin-top: -10px;" prop="tskStufsList">
          <el-checkbox-group v-model="dataForm.tskStufsList">
            <el-checkbox v-for="leader in taskleader" :key="leader.userId" :label="leader.userId" :value="leader.userId"
              :title="leader.remark">
              <span v-if="leader.remark.length > 6" :title="leader.remark" class="ellipsis">{{
                leader.remark.substring(0,6) }}...</span>
              <span v-else>{{ leader.remark }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
      <!--工作人员-->
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作人员">
            <el-checkbox @change="handleCheckAllChange2" v-model="allStufs2">全选</el-checkbox>
          </el-form-item>
        </el-col>
        <el-form-item style="margin-top: -10px;" prop="tskPrincipalsList">
          <el-checkbox-group v-model="dataForm.tskPrincipalsList">
            <el-checkbox v-for="leader in tskWork" :key="leader.userId" :label="leader.userId" :value="leader.userId"
              :title="leader.remark">
              <span v-if="leader.remark.length > 6" :title="leader.remark" class="ellipsis">{{
                leader.remark.substring(0,6) }}...</span>
              <span v-else>{{ leader.remark }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
      <!-- 业务员 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="业务员">
            <el-checkbox @change="handleCheckAllChange3" v-model="allStufs3">全选</el-checkbox>
          </el-form-item>
        </el-col>
        <el-form-item style="margin-top: -10px;" prop="tskClerkList">
          <el-checkbox-group v-model="dataForm.tskClerkList">
            <el-checkbox v-for="leader in tssalesman" :key="leader.userId" :label="leader.userId" :value="leader.userId"
              :title="leader.remark">
              <span v-if="leader.remark.length > 6" :title="leader.remark" class="ellipsis">{{
                leader.remark.substring(0,6) }}...</span>
              <span v-else>{{ leader.remark }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
      <!-- 备注 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="dataForm.tskRemark" placeholder="请输入" style="height: 50px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 保存 取消 -->
      <el-form-item style="margin-top: 50px;">
        <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
        <el-button @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, reactive, ref, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const allStufs = ref(false); // 全选
const allStufs2 = ref(false); // 全选
const allStufs3 = ref(false); // 全选

const dataForm = reactive({
  loading: false,
  id: null,
  tskName: "",
  tskRemark: "",
  tskClerkList: [] as number[],
  tskStufsList: [] as number[],
  tskPrincipalsList: [] as number[],
  typeList: [1, 6, 7, 3],
  exhId: "",
  tid: null as any, //展会名称
});

// 自定义验证规则
const validateStaffSelection = (rule: any, value: any, callback: any) => {
  if (dataForm.tskPrincipalsList.length > 0 || dataForm.tskClerkList.length > 0) {
    callback();
  } else {
    callback(new Error('请勾选工作人员或者业务员'));
  }
};


//校验
const rules = ref({
  tskName: [
    { required: true, message: '必填项', trigger: 'change', },
  ],
  tskStufsList: [
    { required: true, message: '必填项', trigger: 'change', },
  ],
  // 应用自定义验证规则
  tskClerkList: [
    { validator: validateStaffSelection, trigger: 'change' },
  ],
  tid: [
    { required: true, message: '必填项', trigger: 'change', },
  ],
});

//初始化
const init = (id: number,) => {

  visible.value = true;
  dataForm.id = null;
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  //获取多选框数据
  getTaskleader();
  getTaskWork();
  getTaskWork2();
  getTemplates()

  if (id) {
    getEdit(id)
  }
};


//编辑
const getEdit = (id: number) => {
  baseService.get("/noc/nocrepaytask/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    dataForm.tid = parseInt(res.data.exhId);
  });
};

//展会名称列表
const templates = ref<any[]>([]);
const getTemplates = () => {
  baseService.get('/crm/noctemplate/list', { limit: 300 }).then((res) => {
    if (res.code == 0) {
      //刷新
      templates.value = res.data;
    }
  });
};

//任务负责人
const taskleader = ref([] as any[]);

/**
 * 任务负责人-全选
 * @param val
 */
const handleCheckAllChange = (val: boolean) => {
  dataForm.tskStufsList = [];
  // 选中
  if (val) {
    for (let i = 0; i < taskleader.value.length; i++) {
      dataForm.tskStufsList.push(taskleader.value[i].userId);
    }
  } else {
    dataForm.tskStufsList = [];
  }
}

/**
 * 获取任务负责人
 */
const getTaskleader = () => {
  // 1,6 7:领导 组长 数据组
  return baseService.post("/sys/user/getLeaderList", { typeList: dataForm.typeList.join(), isUserNeedExhId: 0 }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    taskleader.value = res.data;
  });
};


//工作人员
const tskWork = ref([] as any[]);

/**
 * 工作人员-全选
 * @param val
 */
const handleCheckAllChange2 = (val: boolean) => {
  // 选中
  if (val) {
    dataForm.tskPrincipalsList = [];
    for (let i = 0; i < tskWork.value.length; i++) {
      dataForm.tskPrincipalsList.push(tskWork.value[i].userId);
    }
  } else {
    dataForm.tskPrincipalsList = [];
  }
}

/**
 * 获取工作人员
 */
const getTaskWork = () => {
  // 4：工作人员
  return baseService.post("/sys/user/usersByType", { type: 4, isUserNeedExhId: 0 }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    tskWork.value = res.data;
  });
};


//业务员
const tssalesman = ref([] as any[]);

/**
 * 业务员-全选
 * @param val
 */
const handleCheckAllChange3 = (val: boolean) => {
  // 选中
  if (val) {
    dataForm.tskClerkList = [];
    for (let i = 0; i < tssalesman.value.length; i++) {
      dataForm.tskClerkList.push(tssalesman.value[i].userId);
    }
  } else {
    dataForm.tskClerkList = [];
  }
}

/**
 * 获取业务员
 */
const getTaskWork2 = () => {
  // 2 业务员
  return baseService.post("/sys/user/usersByType", { type: 2, isUserNeedExhId: 0 }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    tssalesman.value = res.data;
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    dataForm.loading = true;
    dataForm.tskPrincipalsList = dataForm.tskPrincipalsList.map((item: number) => Number(item));
    dataForm.tskStufsList = dataForm.tskStufsList.map((item: number) => Number(item));

    (!dataForm.id ? baseService.post : baseService.put)(
      "/noc/nocrepaytask",
      {
        id: dataForm.id,
        exhId: dataForm.tid,
        tskName: dataForm.tskName,
        tskStufsList: dataForm.tskStufsList,
        tskPrincipalsList: dataForm.tskPrincipalsList,
        tskClerkList: dataForm.tskClerkList,
        tskRemark: dataForm.tskRemark,
      }).then((res) => {
        ElMessage.success({
          message: t("prompt.success"),
          duration: 500,
          onClose: () => {
            dataForm.loading = false;
            visible.value = false;
            emit("refreshDataList");
          }
        });
      });
  });
};

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.el-checkbox {
  width: 82px;
}
::v-deep .el-form-item__error {
    width: 150px !important;
  }
</style>
